<?php
/* 
 * name        : Module » Blog
 * description : Displays blog content.
 * 
 */

// disable main 404 page
$module_404 = false;


require_once(dirname(__FILE__) . '/includes/get_categories.php');

$category_children = array();
$categories_flat = array();
$categories = blog_get_categories(1, $page['full_path'], 0, $category, $category_children, array(1), $categories_flat);
$filter = array();
$template = '404';

if (!isset($path[0]) or isset($category) or $path[0] == 'tags') {
	/*
	 * All these cases will result in a post listing
	 *
	 */
	if (!isset($path[0])) {
		// we'll want all posts
		$filter['category'] = 1;
		$template = 'index';
	}
	else if ($path[0] == 'tags') {
		$filter['tags'] = array_slice($path, 1);
		$template       = 'tags';
	}
	else if (isset($category)) {
		$path = array_slice($path, substr_count($category['full_path'], '/'));
 		if (!isset($path[0])) {
			$filter['category'] = $category['id'];
			$template           = 'category';
		}
	}
}

else if (isset($path[0]) and preg_match('/^(\d{4})$/', $path[0], $matches)) {
	/*
	 * Archive, or article
	 *
	 */
	$template = 'archive';
	$filter['year'] = $matches[1];
	if (isset($path[1]) and preg_match('/^(\d{2})$/', $path[1], $matches)) {
		$filter['month'] = $matches[1];
		if (isset($path[2]) and preg_match('/^(\d{2})$/', $path[2], $matches)) {
			$filter['day'] = $matches[1];
			if (isset($path[3])) {
				if ($env['blog']['permalink'] == 'YYYY/MM/DD') {
					// yyyy/mm/dd based post
					$filter['path'] = $path[3];
					$template = 'post';
				} else {
					$template = 'post301';
				}
			}
		} else if (isset($path[2])) {
			if ($env['blog']['permalink'] == 'YYYY/MM') {
				// yyyy/mm based post
				$filter['path'] = $path[2];
				$template = 'post';
			} else {
				$template = 'post301';
			}
		}
	} else if (isset($path[1])) {
		if ($env['blog']['permalink'] == 'YYYY') {
			// yyyy based post
			$filter['path'] = $path[1];
			$template = 'post';
		} else {
			$template = 'post301';
		}
	}
	
}


$filter_sql = '1 ';
if (isset($filter['year'])) {
	if (isset($filter['month'])) {
		if (isset($filter['day'])) {
			// year/month/day
			$filter_sql .= "AND published_display >= '{$filter['year']}-{$filter['month']}-{$filter['day']} 00:00:01' AND published_display < '{$filter['year']}-{$filter['month']}-{$filter['day']} 00:00:01' + INTERVAL 1 DAY ";
		} else {
			// year/month
			$filter_sql .= "AND published_display >= '{$filter['year']}-{$filter['month']}-01 00:00:01' AND published_display < '{$filter['year']}-{$filter['month']}-01 00:00:01' + INTERVAL 1 MONTH ";
		}
	} else {
		// year
		$filter_sql .= "AND published_display >= '{$filter['year']}-01-01 00:00:01' AND published_display < '{$filter['year']}-01-01 00:00:01' + INTERVAL 1 YEAR ";
	}
}


if (isset($filter['category'])) {
	$filter_sql .= 'AND (';
	$filter_sql .= $db->quoteInto("category_id=? ", (int)$filter['category']);
	if (isset($category_children[$filter['category']])) {
		foreach($category_children[$filter['category']] as $category_id) {
			$filter_sql .= $db->quoteInto("OR category_id=? ", (int)$category_id);
		}
	}
	$filter_sql .= ')';
}


if (isset($filter['tags'])) {
	if (count($filter['tags'])) {
		$matching_posts = null;
		$tags = $filter['tags'];
		foreach ($tags as $i => $tag) {
			$tags[$i] = $db->quote($tag);
			$result = $db->fetchCol("SELECT p.id FROM blog_posts p JOIN blog_posts_revisions pr ON p.revision_id=pr.id JOIN blog_posts_revisions_tags prt ON pr.id=prt.revision_id JOIN cms_tags t ON prt.tag_id=t.id WHERE t.name={$tags[$i]} AND t.site_id=?", $site['id']);
			$matching_posts = is_null($matching_posts) ? $result : array_intersect($matching_posts, $result);
		}
		$filter_sql .= "AND p.id IN (" . join(',', $matching_posts) . ")";
		$tags = $db->fetchAll("SELECT t.name, COUNT(*) AS count FROM cms_tags t  JOIN blog_posts_revisions_tags prt ON t.id=prt.tag_id  JOIN blog_posts_revisions pr ON prt.revision_id=pr.id JOIN blog_posts p ON pr.id=p.revision_id WHERE p.site_id=? AND t.site_id=? AND p.id IN (" . join(',', $matching_posts) . ") AND t.name NOT IN (" . join(',', $tags) . ") GROUP BY t.id ORDER BY t.name", array($site['id'], $site['id']));
	} else {
		header("Location: {$page['full_path']}");
		exit;
	}
} else { 
	$tags = $db->fetchAll("SELECT t.name, COUNT(*) AS count FROM cms_tags t JOIN blog_posts_revisions_tags prt ON t.id=prt.tag_id JOIN blog_posts_revisions pr ON prt.revision_id=pr.id JOIN blog_posts p ON pr.id=p.revision_id WHERE p.site_id=? AND t.site_id=? GROUP BY t.id ORDER BY t.name", array($site['id'], $site['id']));
}

if (isset($filter['path'])) {
	$filter_sql .= $db->quoteInto("AND path=? ", (string)$filter['path']);
}

$posts = $db->fetchAll("SELECT r.*, p.*, u.display_name AS author FROM blog_posts p LEFT JOIN blog_posts_revisions r ON p.revision_id=r.id LEFT JOIN cms_users u ON r.author_id=u.id WHERE {$filter_sql} AND active=1 AND p.site_id=? ORDER BY published_display DESC", $site['id']);
foreach($posts as $i => $post) { 
	if ($post['category_id'] and isset($categories_flat[$post['category_id']])) $posts[$i]['category'] = $categories_flat[$post['category_id']];
	if ($env['blog']['permalink'] == 'YYYY/MM/DD') {
		$posts[$i]['permalink'] = date('Y/m/d/', strtotime($post['published_display'])) . $post['path'] . '/';
	} else if ($env['blog']['permalink'] == 'YYYY/MM') {
		$posts[$i]['permalink'] = date('Y/m/', strtotime($post['published_display'])) . $post['path'] . '/';
	} else {
		$posts[$i]['permalink'] = date('Y/', strtotime($post['published_display'])) . $post['path'] . '/';
	}
	$posts[$i]['tags'] = $db->fetchCol("SELECT t.name FROM cms_tags t JOIN blog_posts_revisions_tags prt ON t.id=prt.tag_id JOIN blog_posts_revisions pr ON prt.revision_id=pr.id JOIN blog_posts p ON pr.id=p.revision_id WHERE p.id=? ORDER BY t.name", $posts[$i]['post_id']);
	$posts[$i]['comments'] = $db->fetchAll("SELECT * FROM blog_posts_comments WHERE post_id=? ORDER BY timestamp", $posts[$i]['id']);
	foreach($posts[$i]['comments'] as $j => $comment) {
		if ($comment['user_id']) {
			$posts[$i]['comments'][$j]['user'] = $db->fetchRow("SELECT * FROM cms_users WHERE id=?", $comment['user_id']);
		}
	}
}


/*
 * Get archive months
 *
 */
$archive = $db->fetchCol("SELECT DISTINCT DATE_FORMAT(published_display, '%Y-%m-01') AS month FROM blog_posts p JOIN blog_posts_revisions r ON p.revision_id=r.id WHERE active=1 AND site_id=? ORDER BY month DESC", $site['id']);
$smarty->assign('archive', $archive);

/*
 * Process comments
 *
 */
if (!isset($_SESSION['mathcaptcha'])) {
	$_SESSION['mathcaptcha'] = array();
	$_SESSION['mathcaptcha']['num1'] = rand(1,5);
	$_SESSION['mathcaptcha']['num2'] = rand(1,5);
}
if ($template == 'post' and $_POST and isset($_POST['comment'])) {
	$errors = array();
	if (!$_POST['comment']) {
		$errors['comment'] = 1;
	}
	if (isset($_SESSION['login']['user'])) {
		if (count($errors) == 0) {
			$db->insert('blog_posts_comments', array(
				'post_id' => $posts[0]['id'],
				'user_id' => $_SESSION['login']['user']['id'],
				'name'    => $_SESSION['login']['user']['display_name'],
				'email'   => $_SESSION['login']['user']['email'],
				'comment' => $_POST['comment']
			));
			array_push($posts[0]['comments'], $db->fetchRow("SELECT * FROM blog_posts_comments WHERE id=?", $db->lastInsertId()));
			// destroy any mathcaptcha data so that a new challenge is generated next time.
			$_SESSION['mathcaptcha']['num1'] = rand(1,5);
			$_SESSION['mathcaptcha']['num2'] = rand(1,5);
			
			if (isset($_POST['notify']) and $_POST['notify'] and !$db->fetchOne("SELECT post_id FROM blog_posts_subscriptions WHERE post_id=? AND email_address=?", array($posts[0]['id'], $_SESSION['login']['user']['email']))) {
				$db->insert('blog_posts_subscriptions', array(
					'post_id' => $posts[0]['id'],
					'email_address' => $_SESSION['login']['user']['email']
				));
			}
			$_POST = array();
		} else {
			$smarty->assign('errors', $errors);
		}
	} else {
		if (!$_POST['name']) {
			$errors['name'] = 1;
		}
		if (!$_POST['email']) {
			$errors['email'] = 1;
		}
		if ($_POST['mathcaptcha'] != $_SESSION['mathcaptcha']['num1'] + $_SESSION['mathcaptcha']['num2']) {
			$errors['mathcaptcha'] = 1;
		}
		
		if (count($errors) == 0) {
			$db->insert('blog_posts_comments', array(
				'post_id' => $posts[0]['id'],
				'name'    => $_POST['name'],
				'email'   => $_POST['email'],
				'comment' => $_POST['comment']
			));
			array_push($posts[0]['comments'], $db->fetchRow("SELECT * FROM blog_posts_comments WHERE id=?", $db->lastInsertId()));
			$_SESSION['mathcaptcha']['num1'] = rand(1,5);
			$_SESSION['mathcaptcha']['num2'] = rand(1,5);
			
			if ($_POST['notify'] and !$db->fetchOne("SELECT post_id FROM blog_posts_subscriptions WHERE post_id=? AND email_address=?", array($posts[0]['id'], $_POST['email']))) {
				$db->insert('blog_posts_subscriptions', array(
					'post_id' => $posts[0]['id'],
					'email_address' => $_POST['email']
				));
			}
			
			$_POST = array();
		} else {
			$smarty->assign('errors', $errors);
		}
	}
	
}



$tag_info = array('tags' => $tags);
$tag_info['min'] = 9999999999;
$tag_info['max'] = 0;
foreach($tags as $tag) {
	if ($tag['count'] < $tag_info['min']) $tag_info['min'] = $tag['count'];
	if ($tag['count'] > $tag_info['max']) $tag_info['max'] = $tag['count'];
}
$tag_info['delta'] = $tag_info['max'] - $tag_info['min'];

$smarty->assign('categories', $categories);
$smarty->assign('category', $category);
$smarty->assign('template', $template);
$smarty->assign('tag_info', $tag_info);
$smarty->assign('filter', $filter);

if ($template == 'post301') {
	if (isset($posts[0])) {
		// forward incorrect permalinks to correct style
		header("HTTP/1.0 301 Moved Permenantly");
		header("Location: " . $page['full_path'] . '/' . $posts[0]['permalink']);
		exit;
	} else {
		echo '404';
	}
}

else if ($template == 'post') {
	$smarty->assign('post', $posts[0]);
	$smarty->display('blog/post.tpl.html');
} else {
	
	$smarty->assign('posts', $posts);
	if (isset($_GET['feed']) and $_GET['feed'] == 'rss') {
		header('Content-type: application/xml');
		$smarty->display('blog/feed.tpl.' . $_GET['feed']);
	} else {
		header('X-Robots-Tag: noindex');
		$smarty->display('blog/index.tpl.html');
	}
}

